package com.ebupt.migu.music.popup.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ebupt.migu.globalpopup.entity.AdsRedisBean;
import com.ebupt.migu.globalpopup.entity.ConditionRelation;
import com.ebupt.migu.music.commons.constants.ResultMsg;
import com.ebupt.migu.music.commons.utils.ConditionUtil;
import com.ebupt.migu.music.popup.dto.AdsDTO;
import com.ebupt.migu.music.popup.service.AdsService;
import com.ebupt.migu.music.redis.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * 服务云全局弹窗接口
 *
 * @author wangzhu
 * @since 2021-11-17
 */
@Service
@Slf4j
public class AdsServiceImpl implements AdsService {

    @Autowired
    private RedisService redisService;

    /**
     * 判定当前用户是否需要弹出广告
     *
     * @param ads
     * @return
     */
    @Override
    public ResultMsg ads(AdsDTO ads) {
        // 通过activity_type = 6（广告）以及请求参数中的scene的枚举值来确定一条记录；
        log.info("AdsDTO：{}",ads.toString());
        ResultMsg resultMsg = new ResultMsg();
        try {
            resultMsg.setData(false);
            String redisKey = "ads-" + ads.getScene();
            if (redisService.exists(redisKey)) {
                List<AdsRedisBean> adsRedisBean = JSONObject.parseArray(Objects.requireNonNull(redisService.get(redisKey)).toString(), AdsRedisBean.class);
                adsRedisBean.forEach(e -> {
                    List<ConditionRelation> conditionRelations = e.getConditionRelations();
                    if (conditionRelations.size() > 0) {
                        ConditionUtil conditionTool = ConditionUtil.getConditionUtil();
                        boolean b = conditionTool.getCondition(ads.getExtra(), conditionRelations);
                        if (b){
                            // 用户命中,返回人群对应的策略
                            log.info("用户：{}, 命中人群：{}, 广告投放：{}", ads.getDeviceId(), e.getConditionRelations().get(0).getGroupId(), e.getAdsInfo().getIsCast());
                            resultMsg.setData(e.getAdsInfo().getIsCast());
                        }
                    }
                });
            }
            resultMsg.setMessage("SUCCESS");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultMsg;
    }

}
